<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
       <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['userInfo:userInfo:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['userInfo:userInfo:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['userInfo:userInfo:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

      <div>
        <span>总用户：{{ totalForm.infoTotal }}</span></br>
        <span>总用户余额：{{ totalForm.balanceTotal}}</span></br>
        <span>总用户卡数量：{{ totalForm.cardTotal }}</span>
      </div>

    <el-table
      v-loading="loading"
      :data="userInfoList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="昵称" align="center" prop="accountName" />
      <el-table-column label="用户余额" align="center" prop="balance" />
      <el-table-column
        label="用户持有卡片数量"
        align="center"
        prop="cardCount"
      />
      <el-table-column label="冻结积分/SHJC" align="center" prop="freezeAccount" />
      <el-table-column label="冻结卡量/张" align="center" prop="freezeCard" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createdAt"
        width="180"
      >
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, "{y}-{m}-{d}") }}</span>
        </template> -->
      </el-table-column>
      <!-- <el-table-column
        label="更新时间"
        align="center"
        prop="updatedAt"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedAt, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['userInfo:userInfo:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['userInfo:userInfo:remove']"
            >删除</el-button
          >

            <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleUpdatePassWord(scope.row)"
            >修改密码</el-button
          >

           <el-button
            size="mini"
            type="text"
            icon="el-icon-lock"
            @click="handleFreez(scope.row)"
            v-hasPermi="['userInfo:userInfo:freez']"
            v-if="scope.row.status == 1"
            >冻结</el-button
          >

           <el-button
            size="mini"
            type="text"
            icon="el-icon-unlock"
            @click="handleUnFreez(scope.row)"
            v-hasPermi="['userInfo:userInfo:unFreez']"
            v-if="scope.row.status == 0"
            >解冻</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="昵称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <!-- 只在新增时显示密码字段 -->
        <el-form-item label="密码" prop="password" v-if="!form.userId">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="用户余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入用户余额" />
        </el-form-item>
        <el-form-item label="持有卡片数" prop="cardCount">
          <el-input
            v-model="form.cardCount"
            placeholder="请输入用户持有卡片数量"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    
    <!-- 冻结积分对话框 -->
    <el-dialog :title="'冻结'" :visible.sync="freezeDialogVisible" width="400px">
      <el-form ref="form" :model="form" :rules="rules"  label-width="80px">
        <el-form-item label="当前余额" prop="balance">
          <el-input v-model="form.balance" disabled></el-input>
        </el-form-item>
        <el-form-item label="冻结积分/SHJC" prop="freezeAccount">
          <el-input v-model="form.freezeAccount"></el-input>
        </el-form-item>
         <el-form-item label="当前卡量" prop="cardCount">
          <el-input v-model="form.cardCount" disabled></el-input>
        </el-form-item>
        <el-form-item label="冻结卡量/张" prop="freezeCard">
          <el-input v-model="form.freezeCard"></el-input>
        </el-form-item>
          <el-form-item label="冻结原因" prop="freezeReason">
          <el-input v-model="form.freezeReason" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFreeze">确 定</el-button>
        <el-button @click="closeFreezeDialog">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="'修改密码'" :visible.sync="passwordDialogVisible" width="400px">
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="80px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请确认新密码" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPasswordChange">确 定</el-button>
        <el-button @click="closePasswordDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUserInfo,
  getUserInfo,
  delUserInfo,
  addUserInfo,
  updateUserInfo,
  freezeStatusUserInfo,
  freezeAccount,
  unFreezeStatus,
  totalUserInfo,
  updateUserPwd
} from "@/api/userInfo/userInfo";

export default {
  name: "UserInfo",
  data() {
    return {
      // 修改密码弹框
      passwordDialogVisible: false,
      // 修改密码表单
      passwordForm: {
        newPassword: '',
        confirmPassword: '',
      },
      // 修改密码表单校验规则
      passwordRules: {
        newPassword: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
        ],
      },
      // 创建时间
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户信息表格数据
      userInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        email: null,
        phoneNumber: null,
        balance: null,
        cardCount: null,
        createdAt: null,
        updatedAt: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        accountName: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        username: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        freezeAccount: [
          { required: true, message: "冻结积分/SHJC不能为空", trigger: "blur" },
        ],
        freezeCard: [
          { required: true, message: "冻结卡量/张不能为空", trigger: "blur" },
        ],
        freezeReason: [
          { required: true, message: "冻结原因不能为空", trigger: "blur" },
        ],
      },
      freezeDialogVisible: false,
      currentPoints: 0, // 当前积分
      freezeAccount: 0, // 冻结积分
      currentCard: 0, // 当前卡量
      freezeCard: 0, // 冻结卡量/张
      websocket: null, // WebSocket对象
      totalForm: {
        infoTotal: 0,
        balanceTotal:0,
        cardTotal:0
      }
    };
  },
  created() {
    this.getList();
    this.setupWebSocket(); // 创建WebSocket连接

  },
  methods: {
    setupWebSocket() {
        const isDev = process.env.NODE_ENV === 'development';
      // const wsUrl = isDev ? 'ws://www.pc.sanhuijucai.com/ws/message' : 'wss://your-domain.com/ws/message';
      const wsUrl = isDev ? 'ws://localhost:8080/ws/message' : 'wss://www.pc.sanhuijucai.com/ws/message';

      this.websocket = new WebSocket(wsUrl); // 创建WebSocket连接
      this.websocket.onopen = this.onWebSocketOpen; // WebSocket连接打开时的处理函数
      this.websocket.onmessage = this.onWebSocketMessage; // 收到WebSocket消息时的处理函数
      this.websocket.onclose = this.onWebSocketClose; // WebSocket连接关闭时的处理函数
    },
    onWebSocketOpen() {
      console.log("链接成功");

       // 发送初始化消息 根据后端定义的来
    const initMessage = {
      type: 'sub',
      topic: '/aa/bb/cc/d',
      parameter: {},
      id: 'bb',
      };
    
    this.sendMessage(JSON.stringify(initMessage));
    
    },
    sendMessage(message) {
      if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(message); // 发送消息到WebSocket服务器
      }
    },
      onWebSocketMessage(event) {
    const message = event.data;
    // 处理从服务器接收的消息
    console.log('Received message:', message);

    // 在这里您可以根据消息的内容执行不同的操作，例如更新界面、触发事件等
  },
    closeWebSocket() {
      if (this.websocket) {
        this.websocket.close(); // 关闭WebSocket连接
      }
    },
    // 提示是否解冻账户
    handleUnFreez(row) { 
      const _this = this;

          this.$confirm('确认解冻账户余额卡量？确认操作？', '确认操作', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确认',
          cancelButtonText: '解冻账户'
        }).then(() => {
              // 解冻账户
          row.status = 1;
          unFreezeStatus(row).then((response) => {
            console.log("response ===>", response);
            if (response.code == 200) {
              console.log("this",_this);
              _this.$modal.msgSuccess("账户余额卡量解冻成功");
              setTimeout(() => {  
                this.getList();
              }, 1000);
            } else {
              _this.$message.msgError("账户余额卡量解冻失败");
            }
              
          });
        }).catch(action => {
            if (action === 'cancel') {
            // 解冻账户 
            row.status = 1;
              updateUserInfo(row).then((response) => {
                console.log("response ===>", response);
                if (response.code == 200) {
                  console.log("this",_this);
                  _this.$modal.msgSuccess("账户解冻成功");
                  setTimeout(() => {  
                    this.getList();
                  }, 1000);
                } else {
                  _this.$message.msgError("账户解冻失败");
                }
              });
          }
          });
    },
    // 提示是否冻结账户
    handleFreez(row) {
      const _this = this;
      this.form = row;
      this.$modal
        .confirm('确认冻结账户？冻结账户将继续冻结卡和余额，确认操作？')
        .then(function () {
          // 冻结账户
          row.status = 0;
          freezeStatusUserInfo(row).then((response) => {
            console.log("response ===>", response);
            if (response.code == 200) {
              _this.$modal.msgSuccess("账户冻结成功，请继续冻结卡和余额");
            } else {
              _this.$modal.msgError("账户冻结失败");
            }
          });
          return ;
        })
        .then(() => {
          _this.currentPoints = row.balance; // 获取当前积分
          _this.frozenPoints = 0; // 重置冻结积分
          _this.freezeDialogVisible = true;
        })
        .catch(() => {

        });
     
    },
    // 关闭冻结积分对话框
    closeFreezeDialog() {
      this.freezeDialogVisible = false;
    },
    // 提交冻结积分
    submitFreeze() {
      console.log("this.form ===>", this.form);
      if (this.form.freezeAccount === 0 || this.form.freezeCard === 0 || this.form.freezeAccount === undefined || this.form.freezeCard === undefined) {
        this.$message.warning("冻结积分/SHJC和卡量不能为0或空");
        return;
      }
      // 处理冻结积分的逻辑
      const _this = this;
       this.$refs["form"].validate((valid) => {
         if (valid) {
              this.$modal
            .confirm('确认冻结该用户余额卡量？确认操作？')
            .then(function () {
              // 冻结账户
              freezeAccount(_this.form).then((response) => {
                console.log("response ===>", response);
                if (response.code == 200) {
                  _this.$modal.msgSuccess("余额冻结成功！");
                } else {
                  _this.$modal.msgError("余额冻结失败");
                }
              });
              return ;
            }).then(() => {
              this.closeFreezeDialog();
              this.getList();
            }).catch(() => {

            });
          }
         })
      
    },
    // 获取当前积分的函数（示例）
    getCurrentPoints() {
      // 这里可以根据实际情况获取当前积分
      return 100; // 示例值
    },
    /** 查询用户信息列表 */
  async getList() {
    this.loading = true;

     let params = {
        ...this.queryParams,
      };

  if (this.dateRange && this.dateRange.length === 2) {
        params.startTime = this.dateRange[0];
        params.endTime = this.dateRange[1];
      }
    
    
      listUserInfo(params).then((response) => {
        this.userInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });


      /** 统计用户信息数据 */
    const res = await totalUserInfo(params.startTime, params.endTime);
    if (res.code == 200) { 
      this.totalForm = res.data;
    }

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        username: null,
        email: null,
        phoneNumber: null,
        balance: null,
        cardCount: null,
        createdAt: null,
        updatedAt: null,
        startTime: null,
        endTime: null,
      };
      this.dateRange = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      const sysUserId = 0;
      getUserInfo(userId, sysUserId).then((response) => {
        console.log("responsev ===>", response);
        this.form = response.user;
        this.open = true;
        this.title = "修改用户信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != null) {
            updateUserInfo(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserInfo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除用户信息编号为"' + userIds + '"的数据项？')
        .then(function () {
          return delUserInfo(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.userInfoList.length > 0) {
        let params = {
          ...this.queryParams
        };
        if (this.dateRange && this.dateRange.length === 2) {
          params.startTime = this.dateRange[0];
          params.endTime = this.dateRange[1];
        }
        this.download(
          'userInfo/userInfo/export', params, `用户信息数据表${new Date().getTime()}.xlsx`
        );
      } else { 
        this.$message.warning("未查询数据");
      }
 
    },
  handleUpdatePassWord(row) {
    this.passwordDialogVisible = true;
    this.passwordForm = { newPassword: '', confirmPassword: '',userId:row.userId ,sysUserId:row.sysUserId };
  },
  submitPasswordChange() {
    this.$refs['passwordForm'].validate((valid) => {
      if (valid) {
        // 提交密码修改逻辑
        updateUserPwd(this.passwordForm).then((res) => {
          console.log("res ===>", res);
          if (res.code === 200) {
            this.$message.success('密码修改成功');
            this.closePasswordDialog();
          } else {
            this.$message.error('密码修改失败');
          }
        });
      }
    });
  },
  closePasswordDialog() {
    this.passwordDialogVisible = false;
  },
  validateConfirmPassword(rule, value, callback) {
    if (value !== this.passwordForm.newPassword) {
      callback(new Error('两次输入的密码不一致'));
    } else {
      callback();
    }
  }
  },
   
};
</script>
